package com.company.clientscard.server.service;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

import com.company.clientscard.server.dao.GeneralDao;
import com.company.clientscard.server.domain.Client;
import com.company.clientscard.server.domain.Document;

public class DocumentService {
	private GeneralDao dao;

	@Required
	public void setDao(GeneralDao dao) {
		this.dao = dao;
	}

	@Transactional(readOnly = true)
	public Document findById(Long id) {
		return (Document) dao.findById(Document.class, id);
	}

	@Transactional
	public void save(Document object) {
		dao.save(object);
	}

	@Transactional
	public Document update(Document object) {
		dao.update(object);
		return (Document) dao.findById(object.getClass(), object.getId());
	}

	@Transactional(readOnly = true)
	public List<Document> findAll(Class<Document> clazz) {
		return dao.findAll(clazz);
	}

	@Transactional(readOnly = true)
	public List<Document> findWithExpression(Class<Document> clazz,
			int firstRow, int numberOfRows, Date date1, Date date2) {

		return dao.findWithExpression(clazz, firstRow, numberOfRows, date1,
				date2);
	}

	@Transactional(readOnly = true)
	public List<Document> findWithParam(Class<Document> clazz,
			String paramName, Object param) {

		return dao.findWithParam(clazz, paramName, param);
	}

	@Transactional(readOnly = true)
	public Long getBalance(Client client, Date date) {
		Criteria criteria = dao.getDaoSession().createCriteria(Document.class);
		criteria.add(Restrictions.lt("docDate", date));
		criteria.setProjection(Projections.sum("sum"));
		Long balance = (Long) criteria.uniqueResult();

		return balance;
	}
}
